<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.currentId ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @onclick="onSubmit()"
    >
      <el-form-item
        label="活动标题"
        prop="title"
      >
        <el-input
          v-model="dataForm.title"
          controls-position="right"
          :min="0"
          label="活动标题"
        />
      </el-form-item>
      <el-form-item
        label="活动封面"
        prop="coverImage"
      >
        <pic-upload
          v-model="dataForm.coverImage"
          @update:model-value="checkImage"
        />
      </el-form-item>
      <el-form-item
        label="活动描述"
        prop="description"
        :rules="[
          { required: false, pattern: /\s\S+|S+\s|\S/, message: '请输入正确的活动描述', trigger: 'blur' }
        ]"
      >
        <el-col>
          <el-input
            v-model="dataForm.description"
            type="textarea"
            :autosize="{minRows: 3, maxRows: 5}"
            placeholder="活动描述"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        label="活动类型"
        prop="type"
      >
        <el-select
          v-model="dataForm.type"
          placeholder="请选择"
        >
          <el-option
            key="online"
            label="线上"
            value="online"
          />
          <el-option
            key="offline"
            label="线下"
            value="offline"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="开始时间"
        prop="startTime"
      >
        <el-date-picker
          v-model="dataForm.startTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item
        label="结束时间"
        prop="endTime"
      >
        <el-date-picker
          v-model="dataForm.endTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item
        label="活动老师"
        prop="teacherName"
      >
        <el-autocomplete
          v-model="dataForm.teacherName"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.type === 'offline'"
        label="活动地点"
        prop="location"
      >
        <el-input
          v-model="dataForm.location"
          controls-position="right"
          :min="0"
          label="活动地点"
        />
      </el-form-item>
      <el-form-item
        label="最大参与人数"
        prop="maxParticipants"
      >
        <el-input-number
          v-model="dataForm.maxParticipants"
          controls-position="right"
          :min="1"
        />
      </el-form-item>
      <el-form-item
        label="活动参与费用"
        prop="activityCost"
      >
        <el-input-number
          v-model="dataForm.activityCost"
          :precision="2"
          :min="0.1"
        />
      </el-form-item>
      <el-form-item
        label="活动缩略图"
        prop="coverPic"
      >
        <pic-upload
          v-model="dataForm.coverPic"
          @update:model-value="checkPic"
        />
      </el-form-item>
      <el-form-item
        label="活动标签"
        prop="activityTag"
      >
        <el-tag
          v-for="tag in tagParam.dynamicTags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{
            tag
          }}
        </el-tag>
        <el-input
          v-if="tagParam.inputVisible"
          ref="saveTagInput"
          v-model="tagParam.inputValue"
          size="small"
          class="input-new-tag"
          @keydown.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button
          v-else
          size="small"
          class="button-new-tag"
          @click="showInput"
        >
          + New Tag
        </el-button>
      </el-form-item>
      <el-form-item
        label="是否推荐"
        prop="isPush"
      >
        <el-switch
          v-model="dataForm.isPush"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item
        label="活动介绍"
        prop="activityInfo"
      >
        <tiny-mce
          ref="contentRef"
          v-model="dataForm.activityInfo"
          style="width:100%"
        />
      </el-form-item>
      <el-table
        :data="dataForm.subList"
        border
        style="width: 100%;"
        class="table-con"
      >
        <el-table-column
          header-align="center"
          align="center"
          label="活动特点"
          min-width="20%"
        >
          <template #default="scope">
            <el-form-item
              :prop="`subList.${scope.$index}.title`"
              label-width="0px"
            >
              <el-input
                v-model="scope.row.title"
                controls-position="right"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="特点描述"
          min-width="80%"
        >
          <template #default="scope">
            <el-form-item
              label-width="0"
              :prop="`subList.${scope.$index}.description`"
            >
              <el-input
                v-model="scope.row.description"
                type="textarea"
                :autosize="{minRows: 3, maxRows: 5}"
                placeholder="活动描述"
              />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <div
        style="margin-top: 20px"
      >
        <el-button
          type="primary"
          icon="el-icon-location-outline"
          @click="addCharacteristic()"
        >
          点击添加活动特色
        </el-button>
        <el-button
          v-if="dataForm.subList.length > 0"
          type="danger"
          @click="delSubList()"
        >
          删除最后一行
        </el-button>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ElMessage} from 'element-plus'
import {Debounce} from '@/utils/debounce'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataForm = reactive({
  id: 0,
  currentId: 0,
  title: '',
  status: 0,
  parentId: 0,
  isPush: 0,
  coverImage: '',
  subList: []
})
const dataRule = reactive({
  title: [
    {required: true, message: '活动标题不能为空', trigger: 'blur'}
  ],
  coverImage: [
    {required: true, message: '活动封面图片不能为空', trigger: 'blur'}
  ]
})
const isSubmit = ref(false)
const dataFormRef = ref(null)
const tagParam = reactive({
  dynamicTags: [],
  inputVisible: false,
  inputValue: ''
})
const init = (id) => {
  visible.value = true
  dataForm.currentId = id || 0
  dataForm.id = id || 0
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  if (dataForm.id) {
    // 修改
    http({
      url: http.adornUrl(`/admin/activity/info/${dataForm.id}`),
      method: 'get',
      params: http.adornParams()
    })
      .then(({data}) => {
        visible.value = true
        dataForm.id = data.id
        dataForm.title = data.title
        dataForm.coverImage = data.coverImage
        dataForm.description = data.description
        dataForm.type = data.type
        dataForm.startTime = data.startTime
        dataForm.endTime = data.endTime
        dataForm.location = data.location
        dataForm.maxParticipants = data.maxParticipants
        dataForm.teacherId = data.teacherId
        dataForm.teacherName = data.teacherName
        dataForm.activityCost = data.activityCost
        dataForm.coverPic = data.coverPic
        dataForm.isPush = data.isPush
        dataForm.activityInfo = data.activityInfo
        tagParam.dynamicTags = JSON.parse(data.activityTag)
        dataForm.subList = data.subList
      })
  } else {
    // 初始化
    tagParam.dynamicTags = []
    dataForm.description = null
    dataForm.isPush = 0
    dataForm.subList = []
  }
  getTeacherList()
}
defineExpose({init})

// 表单提交
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit.value) {
        return
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/admin/activity/' + (dataForm.id ? 'update' : 'add')),
        method: 'post',
        data: http.adornData({
          id: dataForm.id || undefined,
          title: dataForm.title,
          coverImage: dataForm.coverImage,
          description: dataForm.description,
          type: dataForm.type,
          startTime: dataForm.startTime,
          endTime: dataForm.endTime,
          location: dataForm.location,
          maxParticipants: dataForm.maxParticipants,
          teacherId: dataForm.teacherId,
          teacherName: dataForm.teacherName,
          activityCost: dataForm.activityCost,
          coverPic: dataForm.coverPic,
          isPush: dataForm.isPush,
          activityInfo: dataForm.activityInfo,
          activityTag: JSON.stringify(tagParam.dynamicTags),
          subList: dataForm.subList
        })
      })
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              isSubmit.value = false
              visible.value = false
              emit('refreshDataList')
            }
          })
        })
    }
  })
})

/**
 * 重新校验表单pic字段
 */
const checkImage = () => {
  dataFormRef.value?.validateField('coverImage')
}
const checkPic = () => {
  dataFormRef.value?.validateField('coverPic')
}

/**
 * 活动标签
 */
const handleClose = (tag) => {
  tagParam.dynamicTags.splice(tagParam.dynamicTags.indexOf(tag), 1)
}
const showInput = () => {
  tagParam.inputVisible = true
  this.$nextTick(() => {
    this.$refs.saveTagInput.$refs.input.focus()
  })
}
const handleInputConfirm = () => {
  const inputValue = tagParam.inputValue
  if (inputValue) {
    tagParam.dynamicTags.push(inputValue)
  }
  tagParam.inputVisible = false
  tagParam.inputValue = ''
}

/**
 * 添加活动特点
 */
const addCharacteristic = () => {
  dataForm.subList.push({})
}

const delSubList = () => {
  dataForm.subList.pop()
}

/**
 * input的搜索
 */
const inputData = reactive({
  restaurants: [],
  state: '',
  timeoutFun: null
})
const querySearchAsync = (queryString, cb) => {
  const restaurants = inputData.restaurants
  const results = queryString ? restaurants.filter(createStateFilter(queryString)) : restaurants
  clearTimeout(inputData.timeoutFun)
  inputData.timeoutFun = setTimeout(() => {
    cb(results)
  }, 3000 * Math.random())
}

const createStateFilter = (queryString) => {
  return (state) => {
    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
  }
}

const getTeacherList = () => {
  http({
    url: http.adornUrl('/admin/user/list'),
    method: 'get',
    params: http.adornParams({roleId: 1})
  })
    .then(({data}) => {
      const list = []
      for (let i = 0; i < data.length; i++) {
        const obj = {
          value: data[i].realName,
          teacherId: data[i].userId
        }
        list.push(obj)
      }
      inputData.restaurants = list
    })
}
const handleSelect = (item) => {
  dataForm.teacherName = item.value
  dataForm.teacherId = item.teacherId
}
</script>

<style scoped>
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
